package com.shengwei.truck.driver.view.ui.statistic;

import android.content.Intent;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.Observer;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.BarLineChartBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.MPPointF;
import com.google.android.material.chip.Chip;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.JsonStatisticsOneDayData;
import com.shengwei.truck.driver.bean.JsonStatisticsYmdData;
import com.shengwei.truck.driver.bean.MyAxisValueFormatter;
import com.shengwei.truck.driver.bean.MyDateTimeField;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.databinding.ActivityHistroyStatisticBinding;
import com.shengwei.truck.driver.utils.DateTimeUtils;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.view.selfview.chart.XAxisMonthValueFormatter;
import com.shengwei.truck.driver.view.selfview.chart.XAxisWeekValueFormatter;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.view.ui.common.DatePickerFragment;
import com.shengwei.truck.driver.vm.HistoryStatisticViewModel;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import static android.view.View.GONE;

/*
   统计历史
 */
public class HistroyStatisticActivity extends BaseActivity<HistoryStatisticViewModel, ActivityHistroyStatisticBinding> implements View.OnClickListener, OnChartValueSelectedListener {
    String TAG = "HistroyStatisticActivity";
    private int mCurCheckedId;
    //用于翻看上一周，下一周
    private Date mWeekStartDate;
    private Date mWeekEndDate;
    //用于翻看上一月，下一月
    private Date mMonthStartDate;
    private Date mMonthEndDate;
    //翻看年
    private int mYear;
    //用于日统计
    private long mEndTimeMill;
    //传递给服务器的 开始和结束毫秒数
    //private long mStartDateMsParam;
    // private long mEndDateMsParam;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        getLastIntent();
        initLiveDataObersve();
    }

    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {
        //监听日数据
        mViewModel.getStatisticData().observe(this, new Observer<Result<JsonStatisticsOneDayData>>() {
            @Override
            public void onChanged(Result<JsonStatisticsOneDayData> jsonCurUserInfoDataResult) {
                jsonCurUserInfoDataResult.handler(new OnCallback<JsonStatisticsOneDayData>() {
                    @Override
                    public void onSuccess(JsonStatisticsOneDayData data) {
                        updateStasticsUI(data);
                    }
                });
            }
        });

        //监听周数据
        mViewModel.getStatisticWeek().observe(this, new Observer<Result<JsonStatisticsYmdData>>() {
            @Override
            public void onChanged(Result<JsonStatisticsYmdData> jsonStatisticsYmdDataResult) {
                jsonStatisticsYmdDataResult.handler(new OnCallback<JsonStatisticsYmdData>() {
                    @Override
                    public void onSuccess(JsonStatisticsYmdData data) {
                        //填充图表数据
                        ArrayList<String> weights = data.getOption();//周图表数据
                        String total = data.getTotal();  //周总量
                        updateChartUI(0,weights,total);
                    }
                });
            }
        });
        //监听月数据
        mViewModel.getStatisticMonth().observe(this, new Observer<Result<JsonStatisticsYmdData>>() {
            @Override
            public void onChanged(Result<JsonStatisticsYmdData> jsonStatisticsYmdDataResult) {
                jsonStatisticsYmdDataResult.handler(new OnCallback<JsonStatisticsYmdData>() {
                    @Override
                    public void onSuccess(JsonStatisticsYmdData data) {
                        ArrayList<String> weights = data.getOption();
                        String total = data.getTotal();
                        updateChartUI(1,weights,total);
                    }
                });
            }
        });
        //监听年数据
        mViewModel.getStatisticYear().observe(this, new Observer<Result<JsonStatisticsYmdData>>() {
            @Override
            public void onChanged(Result<JsonStatisticsYmdData> jsonStatisticsYmdDataResult) {
                jsonStatisticsYmdDataResult.handler(new OnCallback<JsonStatisticsYmdData>() {
                    @Override
                    public void onSuccess(JsonStatisticsYmdData data) {
                        ArrayList<String> weights = data.getOption();
                        String total = data.getTotal();
                        updateChartUI(2,weights,total);
                    }
                });
            }
        });
    }

    public void updateChartUI(int type, ArrayList<String> weights, String total) {
        if (weights != null) {
            int size = weights.size();
            if (size > 0) {
                switch (type) {
                    case 0:  //周
                        initWeekOrYearDataForChart(size, mDataBinding.chartWeek, weights, 0);
                        break;
                    case 1:  //月
                        initMonthDataForChart(size, weights);
                        break;
                    case 2:  //年
                        initWeekOrYearDataForChart(size, mDataBinding.chartYear, weights, 2);
                        break;
                }
            }
        }
        //更新周总量
        if (!TextUtils.isEmpty(total)) {
            mDataBinding.tvSumWeightValue.setText(total);
        }
    }

    /**
     * 显示统计数据
     *
     * @param data
     */
    private void updateStasticsUI(JsonStatisticsOneDayData data) {
        mDataBinding.statisticMainLayout.loadWeightValue.setText(data.getLaTotal());
        mDataBinding.statisticMainLayout.unLoadWeightValue.setText(data.getUaTotal());
        mDataBinding.statisticMainLayout.timesValue.setText(data.getTrainNumber());
        mDataBinding.statisticMainLayout.tvPlanValue.setText(data.getTaskTotal()+"吨");
    }

    /**
     * 计算今天所在周 的 起始日期和结束日期，并去调用接口获取对应时间段的统计数据
     */
    private void initWeek() {
        //step1. 计算本周第1天和最后1天，并更新 “时间段选择”UI显示
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        refreshWeekDateUI(date);
    }

    /**
     * 计算指定日期所在周的第1天和最后1天，并更新UI显示
     *
     * @param date
     * @return 返回所在周的第1天和最后1天的毫秒数，作为调用服务器 “统计接口” 的参数
     */
    public void refreshWeekDateUI(Date date) {
        //获得date所在周的第一天
        Date weekStartDate = DateTimeUtils.getWeekFirstDay(date);
        MyDateTimeField dateTimeFieldStart = DateTimeUtils.getTimeFieldObject(weekStartDate.getTime());

        //获得date所在周的最后一天
        Date weekEndDate = DateTimeUtils.getWeekEndDay(date);
        MyDateTimeField dateTimeFieldEnd = DateTimeUtils.getTimeFieldObject(weekEndDate.getTime());

        //更新界面
        mDataBinding.tvSelDateStart.setText(dateTimeFieldStart.year + "年" + dateTimeFieldStart.month + "月" + dateTimeFieldStart.day + "日");
        mWeekStartDate = weekStartDate;
        mDataBinding.tvSelDateEnd.setText("~" + dateTimeFieldEnd.month + "月" + dateTimeFieldEnd.day + "日");
        mWeekEndDate = weekEndDate;

        //获得这周时间段的 开始时间毫秒数与结束时间毫秒数，作为调用服务器接口的参数
        Calendar calendar = Calendar.getInstance();
        calendar.set(dateTimeFieldStart.year, dateTimeFieldStart.month - 1, dateTimeFieldStart.day, 0, 0, 0);
        long mStartDateMsParam = calendar.getTimeInMillis();
        calendar.set(dateTimeFieldEnd.year, dateTimeFieldEnd.month - 1, dateTimeFieldEnd.day, 23, 59, 59);
        long mEndDateMsParam = calendar.getTimeInMillis();
        printLog(mStartDateMsParam, mEndDateMsParam);

        //step2. 在这里请求服务器的统计数据
        mViewModel.getStatisticByYmd(0, 0, 0, mStartDateMsParam, mEndDateMsParam);
    }


    private void updateSelYearUI(int year) {
        Calendar calendar = Calendar.getInstance();
        //1年的第1天开始时间
        calendar.set(year, 0, 1, 0, 0, 0);
        long mStartDateMsParam = calendar.getTimeInMillis();
        //1年的最后1天结束时间
        calendar.set(year, 11, 31, 23, 59, 59);
        long mEndDateMsParam = calendar.getTimeInMillis();

        mDataBinding.tvSelDateStart.setText(String.valueOf(year) + "年");
        mDataBinding.tvSelDateEnd.setText("");
        printLog(mStartDateMsParam, mEndDateMsParam);
        mViewModel.getStatisticByYmd(2, year, 0, 0, 0);
    }

    private void printLog(long startTime, long endTime) {
        MyLogCat.i(TAG, "okhttp startTime ymd-hms:" + DateTimeUtils.timeStampToDateString(startTime));
        MyLogCat.i(TAG, "okhttp endTime ymd-hms:" + DateTimeUtils.timeStampToDateString(endTime));
    }

    private void refreshLastYear() {
        mYear--;
        updateSelYearUI(mYear);
    }

    private void refreshNextYear() {
        mYear++;
        updateSelYearUI(mYear);
    }


    //初始化今年的图表数据
    private void initYear() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        mYear = year;
        updateSelYearUI(mYear);


    }

    //初始化今天所在月的起始日期和结束日期
    private void initMonth() {
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        //得到指定日期所在月的第一天的日期
        Date firstDayOfMonth = DateTimeUtils.getMonthFirstDay(date);
        Date endDayOfMonth = DateTimeUtils.getMonthEndDay(date);
        mMonthStartDate = firstDayOfMonth;
        mMonthEndDate = endDayOfMonth;
        updateSelMonthUI(firstDayOfMonth, endDayOfMonth);

    }


    /**
     * 根据当前所选月的第1天，计算出上一个月的第1天和最后1天，并且
     * 刷新上一个月的第1天到最后1天的图表数据
     *
     * @param curMonthStartDate：当前正在显示的月的第1天
     */
    private void refreshLastMonthDate(Date curMonthStartDate) {
        //获取指定日期的上一个月的日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(curMonthStartDate); //指定日期
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) - 1, 1);       // -1上个月
        Date lastMonthDate = calendar.getTime();

        //获取指定日期（上一个月的日期）的第1天和最后1天
        Date firstDayOfMonth = DateTimeUtils.getMonthFirstDay(lastMonthDate);
        Date endDayOfMonth = DateTimeUtils.getMonthEndDay(lastMonthDate);
        mMonthStartDate = firstDayOfMonth;
        mMonthEndDate = endDayOfMonth;
        updateSelMonthUI(firstDayOfMonth, endDayOfMonth);

    }

    /**
     * 根据当前所选月的最后1天，计算出下一个月的第1天和最后1天，并且
     * 刷新下一个月的第1天到最后1天的图表数据
     *
     * @param curMonthEndDate：当前正在显示的月的最后1天
     */
    private void refreshNextMonthDate(Date curMonthEndDate) {
        //setp1 获取指定日期的下一个月的日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(curMonthEndDate); //指定日期
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, 1);       // -1上个月
        Date lastMonthDate = calendar.getTime();

        //setp2 获取lastMonthDate日期所在月中的第1天和最后1天
        Date firstDayOfMonth = DateTimeUtils.getMonthFirstDay(lastMonthDate);
        Date endDayOfMonth = DateTimeUtils.getMonthEndDay(lastMonthDate);
        mMonthStartDate = firstDayOfMonth;
        mMonthEndDate = endDayOfMonth;

        //用月的第1天和最后1天更新UI中的时间选择界面，及其对应的图表数据
        updateSelMonthUI(firstDayOfMonth, endDayOfMonth);
    }

    /**
     * 用月的第1天和最后1天更新UI中的时间选择界面，并调用接口获取第1天到最后1天的统计数据
     *
     * @param firstDayOfMonth：所选月的第1天
     * @param endDayOfMonth：所选月的最后1天
     */
    private void updateSelMonthUI(Date firstDayOfMonth, Date endDayOfMonth) {
        //更新时间范围选择控件
        long mStartDateMsParam = firstDayOfMonth.getTime();
        long mEndDateMsParam = endDayOfMonth.getTime();
        MyDateTimeField dateTimeMonthStart = DateTimeUtils.getTimeFieldObject(mStartDateMsParam);
        MyDateTimeField dateTimeMonthEnd = DateTimeUtils.getTimeFieldObject(mEndDateMsParam);
        int year = dateTimeMonthStart.year;
        int month = dateTimeMonthStart.month;
        int day = dateTimeMonthStart.day;
        int endDay = dateTimeMonthEnd.day;
        mDataBinding.tvSelDateStart.setText(year + "年" + month + "月" + day + "日");
        mDataBinding.tvSelDateEnd.setText("~" + month + "月" + endDay + "日");

        //准备调用接口去获取统计数据
        //计算出所选月的第1天的开始时间0:0：0秒的毫秒数
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day, 0, 0, 0);
        mStartDateMsParam = calendar.getTimeInMillis();
        //计算出所选月的最后1天的结束始时间23:59:59秒的毫秒数
        calendar.set(year, month - 1, endDay, 23, 59, 59);
        mEndDateMsParam = calendar.getTimeInMillis();
        printLog(mStartDateMsParam, mEndDateMsParam);
        mViewModel.getStatisticByYmd(1, year, month, 0, 0);
    }


    /**
     * 获取“指定日期” 的上一周的起始日期和结束日期 并显示
     *
     * @param curWeekStartDate： 指定日期，所选周的起始日期，即周的第一天
     */
    public void refreshLastWeekDate(Date curWeekStartDate) {
        //获取curWeekStartDate的上一周的日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(curWeekStartDate);
        calendar.add(Calendar.DAY_OF_MONTH, -7);
        Date date = calendar.getTime();
        //刷新指定日期 所在周 的 起始日期 和 结束日期
        refreshWeekDateUI(date);
    }

    /**
     * 获取“指定日期” 的下一周的起始日期和结束日期
     *
     * @param curWeekEndDate： 指定日期，所选周的结束日期，即周的最后一天
     */
    public void refreshNextWeekDate(Date curWeekEndDate) {
        //获取curWeekStartDate的上一周的日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(curWeekEndDate);
        calendar.add(Calendar.DAY_OF_MONTH, 7);
        Date date = calendar.getTime();
        //刷新指定日期 所在周 的 起始日期 和 结束日期，在这里为上一周的某个日期所在周的起始和结束日期
        refreshWeekDateUI(date);
    }


    private void initView() {
        mDataBinding.statisticMainLayout.btDateSel.setVisibility(View.VISIBLE);
        mDataBinding.statisticMainLayout.btDateSel.setOnClickListener(this);
        mDataBinding.statisticMainLayout.dateLayout.setOnClickListener(this);

/*        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mDataBinding.statisticMainLayout.statisticDayLayout.getLayoutParams();
        params.setMargins(0, 10, 0, 0);
        mDataBinding.statisticMainLayout.statisticDayLayout.setLayoutParams(params);*/

        mDataBinding.weekLayout.setOnClickListener(this);
        mDataBinding.monthLayout.setOnClickListener(this);
        mDataBinding.yearLayout.setOnClickListener(this);

        mDataBinding.imvLeftArrow.setOnClickListener(this);
        mDataBinding.imvRightArrow.setOnClickListener(this);



        initTitleLayout();
        initChart();
        initData();
    }

    private void initData() {
        //初始某一天的数据
        long curTimeMills = System.currentTimeMillis();
        refreshDayStatistics(curTimeMills);
        //初始图表数据（默认选择周）
        mCurCheckedId = R.id.monthLayout;
        onTitleChecked(R.id.monthLayout);
    }
    /**
     * 更新此刻时间，并从服务器获取最新统计
     */
    public void refreshDayStatistics(long endTimeMills) {
        updateDateTimeUI(endTimeMills);
        String ymd=  DateTimeUtils.getDateTimeYMD(endTimeMills);
        mViewModel.getStatisticOneDay(ymd);
    }
    /**
     * 更新UI上的时间
     */
    public void updateDateTimeUI(long endTimeMills){
        MyDateTimeField myDateTimeField = DateTimeUtils.getTimeFieldObject(endTimeMills);
        //年月日
        String strDateBuilder = myDateTimeField.year + "年" +
                myDateTimeField.month + "月" +
                myDateTimeField.day + "日";
        mDataBinding.statisticMainLayout.tvDate.setText(strDateBuilder);
    }

    /**
     * 初始化title全灰
     */
    private void initTitleLayout() {
        int colorGray = this.getResources().getColor(R.color.btn_text_color);
        mDataBinding.tvWeekTitle.setTextColor(colorGray);
        mDataBinding.tvMonthTitle.setTextColor(colorGray);
        mDataBinding.tvYearTitle.setTextColor(colorGray);

        mDataBinding.cursorWeek.setVisibility(GONE);
        mDataBinding.cursorMonth.setVisibility(GONE);
        mDataBinding.cursorYear.setVisibility(GONE);
    }

    /**
     * 初始化图表
     */
    private void initChart() {
        initWeekChart();
        initMonthChart();
        initYearChart();
    }


    private void initYearChart() {
        mDataBinding.chartYear.setOnChartValueSelectedListener(null);
        mDataBinding.chartYear.setDrawBarShadow(false);
        mDataBinding.chartYear.setDrawValueAboveBar(true);
        mDataBinding.chartYear.getDescription().setEnabled(false);
        mDataBinding.chartYear.setMaxVisibleValueCount(31);
        // scaling can now only be done on x- and y-axis separately
        mDataBinding.chartYear.setScaleEnabled(true); //禁止缩放
        mDataBinding.chartYear.setDrawGridBackground(false);
        mDataBinding.chartYear.getAxisRight().setEnabled(false);//不需要右边的Y轴

        //设置Y轴
        IAxisValueFormatter custom = new MyAxisValueFormatter();
        YAxis leftAxis = mDataBinding.chartYear.getAxisLeft();
        leftAxis.setLabelCount(8, false);
        leftAxis.setValueFormatter(custom);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(10f);//设置最大值至TOP的距离
        setYAxisTextColor(leftAxis);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        //设置X轴
        XAxis xAxis = mDataBinding.chartYear.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        IAxisValueFormatter xAxisFormatter = new XAxisWeekValueFormatter(mDataBinding.chartYear, 2);
        setXAxisValueFormat(mDataBinding.chartYear, xAxisFormatter, 12, 1);

        //禁止图例
        Legend l = mDataBinding.chartYear.getLegend();
        l.setEnabled(false);
    }

    private void initMonthChart() {
        mDataBinding.chartMonth.setOnChartValueSelectedListener(null);
        mDataBinding.chartMonth.setDrawBarShadow(false);
        mDataBinding.chartMonth.setDrawValueAboveBar(true);
        mDataBinding.chartMonth.getDescription().setEnabled(false);
        mDataBinding.chartMonth.setMaxVisibleValueCount(31);
        // scaling can now only be done on x- and y-axis separately
        mDataBinding.chartMonth.setScaleEnabled(true); //禁止缩放
        mDataBinding.chartMonth.setDrawGridBackground(false);
        mDataBinding.chartMonth.getAxisRight().setEnabled(false);//不需要右边的Y轴

        //设置Y轴
        IAxisValueFormatter custom = new MyAxisValueFormatter();
        YAxis leftAxis = mDataBinding.chartMonth.getAxisLeft();
        leftAxis.setLabelCount(8, false);
        leftAxis.setValueFormatter(custom);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(10f);//设置最大值至TOP的距离
        setYAxisTextColor(leftAxis);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        //设置X轴
        XAxis xAxis = mDataBinding.chartMonth.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        IAxisValueFormatter xAxisFormatter = new XAxisMonthValueFormatter(mDataBinding.chartMonth, 1);
        setXAxisValueFormat(mDataBinding.chartMonth, xAxisFormatter, 12, 1);

        //禁止图例
        Legend l = mDataBinding.chartMonth.getLegend();
        l.setEnabled(false);
    }

    public void initWeekChart() {
        mDataBinding.chartWeek.setOnChartValueSelectedListener(null);
        mDataBinding.chartWeek.setDrawBarShadow(false);
        mDataBinding.chartWeek.setDrawValueAboveBar(true);
        mDataBinding.chartWeek.getDescription().setEnabled(false);
        mDataBinding.chartWeek.setMaxVisibleValueCount(31);
        // scaling can now only be done on x- and y-axis separately
        mDataBinding.chartWeek.setScaleEnabled(true); //禁止缩放
        mDataBinding.chartWeek.setDrawGridBackground(false);
        mDataBinding.chartWeek.getAxisRight().setEnabled(false);//不需要右边的Y轴

        //设置Y轴
        IAxisValueFormatter custom = new MyAxisValueFormatter();
        YAxis leftAxis = mDataBinding.chartWeek.getAxisLeft();
        leftAxis.setLabelCount(8, true);
        leftAxis.setValueFormatter(custom);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(10f);//设置最大值至TOP的距离
        setYAxisTextColor(leftAxis);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        //设置X轴
        XAxis xAxis = mDataBinding.chartWeek.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        IAxisValueFormatter xAxisFormatter = new XAxisWeekValueFormatter(mDataBinding.chartWeek, 1);
        setXAxisValueFormat(mDataBinding.chartWeek, xAxisFormatter, 12, 1);

        //禁止图例
        Legend l = mDataBinding.chartWeek.getLegend();
        l.setEnabled(false);
        /*gxw-s
        XYMarkerView mv = new XYMarkerView(this, xAxisFormatter);
        mv.setChartView(mDataBinding.chart); // For bounds control
        mDataBinding.chart.setMarker(mv); // Set the marker to the chart*/

    }
    public void setYAxisTextColor(YAxis leftAxis){
        leftAxis.setTextSize(14);
        int yAxisTextColor = this.getResources().getColor(R.color.btn_text_color);
        leftAxis.setTextColor(yAxisTextColor);
    }

    public void setXAxisValueFormat(BarLineChartBase<?> chart, IAxisValueFormatter xAxisFormatter, int textSize, int granularity) {
        XAxis xAxis = chart.getXAxis();
        xAxis.setGranularity(granularity); // only intervals of 1 day
        xAxis.setTextSize(textSize);
        xAxis.setValueFormatter(xAxisFormatter);
    }

    /**
     * 模拟数据，填充月表
     *
     * @param dayNums
     */
    private void initMonthDataForChart(int dayNums, ArrayList<String> weights) {
        int month = mMonthStartDate.getMonth();
        IAxisValueFormatter xAxisFormatter = new XAxisMonthValueFormatter(mDataBinding.chartMonth,++month);
        setXAxisValueFormat(mDataBinding.chartMonth, xAxisFormatter, 12, 1);
        ArrayList<BarEntry> values = new ArrayList<>();
        for (int dayIndex = 0; dayIndex < dayNums; dayIndex++) {
            float y = Float.parseFloat(weights.get(dayIndex));
            values.add(new BarEntry(dayIndex + 1, y));  //y就是服务器返回的 周数组 每一天对应的 拉货重量
        }
        mDataBinding.chartMonth.invalidate();
        Matrix mMatrix = new Matrix();
        mMatrix.postScale(3f, 1f);
        mDataBinding.chartMonth.getViewPortHandler().refresh(mMatrix, mDataBinding.chartMonth, false);
        mDataBinding.chartMonth.animateY(500);
        refreshChart(mDataBinding.chartMonth, values);
    }


    /**
     * 模拟数据，填充周表
     */
    private void initWeekOrYearDataForChart(int count, BarLineChartBase<?> chart, ArrayList<String> weights, int chartType) {

        IAxisValueFormatter xAxisFormatter = new XAxisWeekValueFormatter(chart, chartType);
        setXAxisValueFormat(chart, xAxisFormatter, 12, 1);
        //设置周的X轴数据格式：周1，周2。。。
       /* weights.set(0,"0");
        weights.set(1,"30");
        weights.set(2,"0");
        weights.set(3,"0");
        weights.set(4,"1");
        weights.set(5,"0");
        weights.set(6,"0");*/

        ArrayList<BarEntry> values = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            float y = Float.parseFloat(weights.get(i));
            values.add(new BarEntry(i + 1, y));  //y就是服务器返回的 周数组 每一天对应的 拉货重量
        }
        chart.animateY(500);
        refreshChart(chart, values);
    }

    public void refreshChart(BarLineChartBase<?> chart, ArrayList<BarEntry> values) {
        BarDataSet set1;
        if (chart.getData() != null && chart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) chart.getData().getDataSetByIndex(0);
            set1.setDrawValues(true);
            set1.setValues(values);
            set1.setHighlightEnabled(false);//gxw+点击不高亮
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(values, "Data Set");
            set1.setDrawValues(true);
            set1.setValueTextSize(14); //设置柱状图顶部字体大小
            int tableColor = this.getResources().getColor(R.color.colorPrimary);
            set1.setColors(tableColor);
            set1.setHighlightEnabled(false);//gxw+点击不高亮;
            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1);
            BarData data = new BarData(dataSets);
            ((BarChart) chart).setData(data);
            ((BarChart) chart).setFitBars(true);
        }
        chart.invalidate();
    }

    private final RectF onValueSelectedRectF = new RectF();

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        if (e == null)
            return;

        RectF bounds = onValueSelectedRectF;
        mDataBinding.chartWeek.getBarBounds((BarEntry) e, bounds);
        MPPointF position = mDataBinding.chartWeek.getPosition(e, YAxis.AxisDependency.LEFT);

        Log.i("bounds", bounds.toString());
        Log.i("position", position.toString());

        Log.i("x-index",
                "low: " + mDataBinding.chartWeek.getLowestVisibleX() + ", high: "
                        + mDataBinding.chartWeek.getHighestVisibleX());

        MPPointF.recycleInstance(position);
    }

    @Override
    public void onNothingSelected() {

    }


    public void dealChipDefaultChecked(int lastCheckedId) {
        ((Chip) this.findViewById(lastCheckedId)).setChecked(true);
    }

    /**
     * 获取上页传递过来的数据,
     * 这里回显上一页的统计数据，无需再请求服务器
     */
    public void getLastIntent() {
        Intent i = this.getIntent();
        Bundle bundle = i.getExtras();
        if (bundle != null) {
            String date = bundle.getString("date");
            String time = bundle.getString("time");
            String loadWeight = bundle.getString("loadWeight");
            String unLoadWeight = bundle.getString("unLoadWeight");
            String times = bundle.getString("times");

            //这里回显上一页的统计数据，无需再请求服务器
            if (!TextUtils.isEmpty(date)) {
                mDataBinding.statisticMainLayout.tvDate.setText(date);
            }

            if (!TextUtils.isEmpty(loadWeight)) {
                mDataBinding.statisticMainLayout.loadWeightValue.setText(loadWeight);
            }

            if (!TextUtils.isEmpty(unLoadWeight)) {
                mDataBinding.statisticMainLayout.loadWeightValue.setText(unLoadWeight);
            }
            if (!TextUtils.isEmpty(times)) {
                mDataBinding.statisticMainLayout.timesValue.setText(times);
            }
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_histroy_statistic;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.weekLayout:
            case R.id.monthLayout:
            case R.id.yearLayout:
                mCurCheckedId = v.getId();
                onTitleChecked(v.getId());
                break;
            case R.id.btDateSel:
            case R.id.dateLayout:
                showDatePicker();
                break;
            case R.id.imvLeftArrow:
                dealLastDate(mCurCheckedId);
                break;
            case R.id.imvRightArrow:
                dealNextDate(mCurCheckedId);
                break;
        }
    }

    private void onTitleChecked(int titleId) {
        initTitleLayout();
        int colorPrimary = this.getResources().getColor(R.color.colorPrimary);
        switch (titleId) {
            case R.id.weekLayout:
                mDataBinding.chartWeek.setVisibility(View.VISIBLE);
                mDataBinding.chartMonth.setVisibility(View.GONE);
                mDataBinding.chartYear.setVisibility(View.GONE);
                mDataBinding.tvWeekTitle.setTextColor(colorPrimary);
                mDataBinding.cursorWeek.setVisibility(View.VISIBLE);
                initWeek();

                break;
            case R.id.monthLayout:
                mDataBinding.chartWeek.setVisibility(View.GONE);
                mDataBinding.chartMonth.setVisibility(View.VISIBLE);
                mDataBinding.chartYear.setVisibility(View.GONE);
                mDataBinding.tvMonthTitle.setTextColor(colorPrimary);
                mDataBinding.cursorMonth.setVisibility(View.VISIBLE);
                initMonth();
                break;
            case R.id.yearLayout:
                mDataBinding.chartWeek.setVisibility(View.GONE);
                mDataBinding.chartMonth.setVisibility(View.GONE);
                mDataBinding.chartYear.setVisibility(View.VISIBLE);
                mDataBinding.tvYearTitle.setTextColor(colorPrimary);
                mDataBinding.cursorYear.setVisibility(View.VISIBLE);
                initYear();
                break;

        }
    }

    /**
     * 处理点击 上一个箭头
     *
     * @param mCurCheckedId
     */
    public void dealLastDate(int mCurCheckedId) {
        if (mCurCheckedId == R.id.weekLayout) {
            refreshLastWeekDate(mWeekStartDate);
        } else if (mCurCheckedId == R.id.monthLayout) {
            refreshLastMonthDate(mMonthStartDate);
        } else if (mCurCheckedId == R.id.yearLayout) {
            refreshLastYear();
        }
    }

    /**
     * 处理点击 上一个箭头
     *
     * @param mCurCheckedId
     */
    public void dealNextDate(int mCurCheckedId) {
        if (mCurCheckedId == R.id.weekLayout) {
            refreshNextWeekDate(mWeekEndDate);
        } else if (mCurCheckedId == R.id.monthLayout) {
            refreshNextMonthDate(mMonthEndDate);
        } else if (mCurCheckedId == R.id.yearLayout) {
            refreshNextYear();
        }
    }

    /**
     * 用DialogFragment显示日期对话框
     */
    public void showDatePicker() {
        DialogFragment newFragment = DatePickerFragment.newInstance(1);
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    /**
     * 选择日期后，请求服务器刷新统计数据
     *
     * @param year  从用DialogFragment中选择的年
     * @param month 选择的月: 索引从0开始，例如3月份month的值将会是2
     * @param day   选择的日
     */
    public void processDatePickerResult(int year, int month, int day) {
        String strYear = Integer.toString(year);
        String strMonth = Integer.toString(month + 1);
        String strDay = Integer.toString(day);
        String strDate = (strYear + "年" + strMonth + "月" + strDay + "日");
        mDataBinding.statisticMainLayout.tvDate.setText(strDate);
        mDataBinding.statisticMainLayout.tvTodayLabel.setVisibility(GONE);

        //刷新统计,提供服务器接口一个开始时间，结束时间
        long startMillisOneDay = DateTimeUtils.getMorningOneDay(year, month, day);  //从早上0点开始
        long endMillisOneDay = DateTimeUtils.getEndTimeOneDay(year, month, day);  //次日0点0分
        printLog(startMillisOneDay, endMillisOneDay);
      //  printTimeLog(startMillisOneDay,endMillisOneDay);
        refreshDayStatistics(endMillisOneDay);
    }

    private void printTimeLog(long startMillisOneDay, long endMillisOneDay) {
        String startDateTime = DateTimeUtils.timeStampToDateString(startMillisOneDay);
        String endDateTime = DateTimeUtils.timeStampToDateString(endMillisOneDay);
        MyLogCat.i(TAG, "startDateTime=" + startDateTime + ",endDateTime=" + endDateTime);
        long gap = (endMillisOneDay - startMillisOneDay);
        long hour = (gap / 1000) / 3600;
        MyLogCat.i(TAG, "gap hour=" + hour);
    }

}